package com.je.workflow.config;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.google.common.base.Strings;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * xxl-job config
 */
@Configuration
public class XxlJobConfig implements EnvironmentAware {

    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        XxlJobSpringExecutor xxlJobSpringExecutor = null;
        Config config = ConfigService.getConfig("xxljob");
        xxlJobSpringExecutor = createExecutor(config);
        return xxlJobSpringExecutor;
    }

    protected XxlJobSpringExecutor createExecutor(Config config) {
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(config.getProperty("xxl.job.admin.addresses", ""));
        xxlJobSpringExecutor.setAppname(config.getProperty("xxl.job.executor.appname", ""));
        xxlJobSpringExecutor.setAddress(config.getProperty("xxl.job.executor.address", ""));
        if (!Strings.isNullOrEmpty(config.getProperty("xxl.job.executor.ip", ""))) {
            xxlJobSpringExecutor.setIp(config.getProperty("xxl.job.executor.ip", ""));
        }
        if (!Strings.isNullOrEmpty(config.getProperty("xxl.job.executor.port", ""))) {
            xxlJobSpringExecutor.setPort(config.getIntProperty("xxl.job.executor.port", 0));
        }
        xxlJobSpringExecutor.setAccessToken(config.getProperty("xxl.job.accessToken", ""));
        if (!Strings.isNullOrEmpty(config.getProperty("xxl.job.executor.logpath", ""))) {
            xxlJobSpringExecutor.setLogPath(config.getProperty("xxl.job.executor.logpath", ""));
        }
        if (!Strings.isNullOrEmpty(config.getProperty("xxl.job.executor.logretentiondays", ""))) {
            xxlJobSpringExecutor.setLogRetentionDays(config.getIntProperty("xxl.job.executor.logretentiondays", 0));
        }
        return xxlJobSpringExecutor;
    }

    @Override
    public void setEnvironment(Environment environment) {

    }
}